//
//  APIBaseManager+APIManager.m
//  BaoZhangWang
//
//  Created by yyy on 2016/12/13.
//  Copyright © 2016年 yyy. All rights reserved.
//

#import "APIBaseManager+APIManager.h"
#import "APICache.h"
#import "APIManagerConfig.h"
#import <CommonCrypto/CommonDigest.h>

static NSTimeInterval kHTTPDefaultCacheOutdateTimeSeconds = 60 * 10; // 10分钟的cache过期时间
static NSTimeInterval kHTTPRequstTimeout = 15;/**< 10秒钟的请求过期时间 */

@implementation APIBaseManager (APIManager)

- (APIRequestMethod)APIMethod {
    return kAPIRequestMethodPOST;
}

- (NSString *)APIScheme {
    return @"http";
}

- (APIRequestSerializerType)APIRequestSerializerType {
    return kAPIRequestSerializerTypeJSON;
}

- (APIResponseSerializerType)APIResponseSerializerType {
    return kAPIResponseSerializerTypeJSON;
}

- (APIRequestPriority)APIRequestPriority {
    return kAPIRequestPriorityDefault;
}

- (NSString *)APIBaseUrl {
    return [APIManagerConfig shareConfig].requestBaseUrl;
}

- (NSTimeInterval)APIHTTPRequestTimeoutInterval {
    return kHTTPRequstTimeout;
}

- (NSDictionary *)APIHTTPHeader {
    return nil;
}

- (NSMutableURLRequest *)APIReformRequest:(NSMutableURLRequest *)request {
    return request;
}

- (id)APIReformParams:(id)params {
    return params;
}

- (id)APIReformResponseObject:(id)responseObject {
    return responseObject;
}

#pragma mark - 缓存

- (BOOL)APIShouldCache {
    return NO;
}

- (BOOL)APIShouldCacheInFile {
    return NO;
}

- (NSString *)APICacheWithVersion {
    return @"";
}

/**
 文件缓存时间，1天
 
 @return 文件缓存时间
 */
- (NSTimeInterval)APIFileCacheTimeOut {
    return 3600 * 24 * 1;
}

/**
 文件缓存的话直接使用文件缓存时间，否则默认10分钟
 
 @return 10
 */
- (NSTimeInterval)APIMemoryCacheTimeOut {
    if (self.APIShouldCacheInFile) {
        return self.APIFileCacheTimeOut;
    } else {
        return kHTTPDefaultCacheOutdateTimeSeconds;
    }
}

- (NSString *)APICacheKey {
    APIBaseManager<APIManager> *manager = (APIBaseManager <APIManager> *)self;
    NSString *path = [manager.APIBaseUrl stringByAppendingPathComponent:manager.APIPath];
    NSString *key = [NSString stringWithFormat:@"Path:%@ Version:%@ Param:%@ header:%@", path, manager.APICacheWithVersion ?: @"", manager.requestParam, manager.APIHTTPHeader];
    return [self transformCacheKey:key];
}

- (NSString *)transformCacheKey:(NSString *)key {
    const char *cStr = [key UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG) strlen(cStr), result);
    NSString *md5String = [NSString stringWithFormat:
                           @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                           result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]
                           ];
    return [md5String uppercaseString];
}

#pragma mark end -

@end
